package com.yupi.yupicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.yupi.yupicturebackend.Exception.ErrorCode;
import com.yupi.yupicturebackend.Exception.ThrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
public class FilePictureUploadImpl extends PictureUploadTemplate {

    private static final long ONE_MB = 1024 * 1024;
    /**
     * @param inputSource
     */
    @Override
    protected void isPictureValid(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        // 1.文件不能为空
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件不能为空！");
        // 2. 文件大小不能超过3M
        // 2.1获取文件大小
        long fileSize = multipartFile.getSize();
        ThrowUtils.throwIf(fileSize > 3 * ONE_MB, ErrorCode.PARAMS_ERROR, "文件大小不能超过3M！");

        // 3. 文件类型校验，校验后缀
        List<String> suffixList = Arrays.asList("jpg", "jpeg", "png", "gif", "bmp", "webp");
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        ThrowUtils.throwIf(!suffixList.contains(fileSuffix), ErrorCode.PARAMS_ERROR, "文件类型错误！");
    }

    /**
     * @param inputSource
     * @param file
     */
    @Override
    protected void processFile(Object inputSource, File file) throws IOException {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        multipartFile.transferTo(file);
    }

    /**
     * @param inputSource
     * @return
     */
    @Override
    protected String getOriginalFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }
}
